import { ReactNode, createContext } from 'react'
import { ReadyState } from '@/types/enum'

interface Options {
  reconnectLimit?: number
  reconnectInterval?: number
  manual?: boolean
  onOpen?: (event: WebSocketEventMap['open'], instance: WebSocket) => void
  onClose?: (event: WebSocketEventMap['close'], instance: WebSocket) => void
  onMessage?: (message: WebSocketEventMap['message'], instance: WebSocket) => void
  onError?: (event: WebSocketEventMap['error'], instance: WebSocket) => void
  protocols?: string | string[]
}

interface Result {
  latestMessage?: WebSocketEventMap['message']
  sendMessage: WebSocket['send']
  disconnect: () => void
  connect: () => void
  readyState: ReadyState
  webSocketIns?: WebSocket
}

export const WebSocketContext = createContext<Result>({} as Result)
export const MyContextProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const socketUrl = 'ws://82.157.123.54:9010/ajaxchattest'
  const onOpen = (e: WebSocketEventMap['open']) => {
    console.log('onOpen', e)
  }
  const options: Options = {
    onOpen,
    manual: true
  }
  const webSocket = useWebSocket(socketUrl, options)

  console.log(webSocket)

  return <WebSocketContext.Provider value={webSocket}>{children}</WebSocketContext.Provider>
}
export const useWebSocketContext = () => useContext(WebSocketContext)

export default {
  MyContextProvider,
  WebSocketContext,
  useWebSocketContext
}
